package wzq.cn.wuziqi.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

import java.util.ArrayList;

import wzq.cn.wuziqi.RC;
import wzq.cn.wuziqi.R;
import wzq.cn.wuziqi.core.OnActionListener;
import wzq.cn.wuziqi.core.OnMoveFinishedListener;
import wzq.cn.wuziqi.model.ChessBoard;
import wzq.cn.wuziqi.model.DrawConfig;
import wzq.cn.wuziqi.model.PointU;
import wzq.cn.wuziqi.utils.LogUtils;
import wzq.cn.wuziqi.utils.Utils;


/**
 * Created by xiawei on 15/8/10.
 */
public class SurfaceViewTempalte extends SurfaceView implements SurfaceHolder.Callback, View.OnTouchListener, OnActionListener {


    private boolean isDebug = true;

    private SurfaceHolder mHolder;

    private boolean isCanTouch = true;

    private Canvas mCanvas;

    /**
     * 保存哪些位置有数据
     */

    private PointU[][] results;
    private int[][] points = new int[RC.MAX_ROW][RC.MAX_ROW];
    //保存可以放棋子的位置 .最低8为表示x ,8-16为表示y
    private int[][] positions = new int[RC.MAX_ROW][RC.MAX_ROW];

    private int numberRow = 10;
    private int winNumber = 5;


    private boolean isRunning = true;
    private boolean needReDraw = true;
    private boolean isInitPosition = false;
    private boolean isTouching = false;

    private PointU mTouchPoint = new PointU();


    private Paint mLinePaint;
    private Paint mWhitePaint;
    private Paint mBlackPaint;


    private int mWidth;
    private int mHeight;
    private int marginEdge = 10;
    private int divRow;

    private ColorSchema colorSchema = ColorSchemaList.schemas.get(0);

    private ArrayList<OnMoveFinishedListener> finishedListeners = new ArrayList<OnMoveFinishedListener>();


    public ColorSchema getColorSchema() {
        return colorSchema;
    }

    public void setColorSchema(ColorSchema colorSchema) {
        this.colorSchema = colorSchema;
        initPaint();
    }

    public int getWinNumber() {
        return winNumber;
    }

    public void setWinNumber(int winNumber) {
        this.winNumber = winNumber;
    }

    /**
     * 注册监听
     *
     * @param listener
     */
    public void registerFinishListener(OnMoveFinishedListener listener) {
        finishedListeners.add(listener);
    }

    /**
     * @param x
     * @param y
     */
    public void notifyMoveFinishObserver(int x, int y) {

        if (checkIfNeedNotify(x, y)) {
            if (finishedListeners != null && finishedListeners.size() > 0) {
                for (OnMoveFinishedListener l :
                        finishedListeners) {
                    l.onMoveFinish(x, y);
                    LogUtils.d("notifyTouch  x = " + x + ",y = " + y);
                }
            }
        } else {
            LogUtils.d("本该通知,却没通知:" + x + "," + y);
        }
    }

    /**
     * 检测是否是有效位置
     *
     * @param x 坐标值x
     * @param y 坐标y
     * @return
     */
    private boolean checkIfNeedNotify(int x, int y) {
        PointU u = finishedListeners.get(0).getBoard().mDeskResult[x][y];
        return u.belong == ChessBoard.SIDE.NONE;
    }

    public int getNumberRow() {
        return numberRow;
    }

    public void setNumberRow(int numberRow) {
        this.numberRow = numberRow;
        isInitPosition = false;
        needReDraw = true;

    }

    private DrawConfig mDrawConfig = new DrawConfig();


    private DrawThread mDrawThread = new DrawThread() {

        @Override
        public void run() {

            for (; isRunning; ) {
                if (needReDraw) {
                    // needReDraw = false;
                    Canvas canvas = null;
                    try {
                        canvas = mHolder.lockCanvas();
                        DrawBackground(canvas);
                        drawTouchPosition(canvas);
                        DrawCurrentState(canvas);

                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        needReDraw = false;
                        mHolder.unlockCanvasAndPost(canvas);
                    }
                }
            }
        }
    };

    /**
     * 正在触摸的点
     *
     * @param canvas
     */
    private void drawTouchPosition(Canvas canvas) {
        if (isTouching) {
            drawByConfig(canvas, mTouchPoint, mDrawConfig);
        }

    }

    private void DrawCurrentState(Canvas canvas) {
        if (finishedListeners.size() > 0) {
            results = finishedListeners.get(0).getBoard().mDeskResult;
            for (int i = 0; i < results.length; i++) {
                PointU[] ps = results[i];
                for (int j = 0; j < ps.length; j++) {
                    PointU p = ps[j];
                    mDrawConfig.x = positions[i][j] & 0xffff;
                    mDrawConfig.y = positions[i][j] >> 16;
                    if (p.belong != ChessBoard.SIDE.NONE) {
                        drawByConfig(canvas, p, mDrawConfig);

                        if (isDebug)
                            LogUtils.d("x=" + mDrawConfig.x + ",y=" + mDrawConfig.y + "i,j" + i + "," + j);
                    }
                }
            }


        }
    }

    /**
     * 画出背景
     *
     * @param canvas
     */
    private void DrawBackground(Canvas canvas) {
        if (numberRow < 8) {
            return;
        }

        canvas.drawColor(getResources().getColor(colorSchema.colorBackground));
        mLinePaint.setColor(getResources().getColor(colorSchema.colorLine));
        divRow = (mWidth - marginEdge * 2) / (numberRow);
        mDrawConfig.r = divRow * 2 / 5;
        float start_x = 0;
        float start_y = 0;
        /**
         * 棋盘高度 高度 -  留边 - 行宽的一半(为顶角的棋子留出空间)
         */

        int startPosition = marginEdge + divRow / 2;
        int broadwidth = (numberRow - 1) * divRow + startPosition;

        initPositionInfos(startPosition, broadwidth);


        for (int i = 0; i < numberRow; i++) {

            start_y = i * divRow + marginEdge + divRow / 2;
            start_x = i * divRow + marginEdge + divRow / 2;
            //横向的
            canvas.drawLine(startPosition, start_y, broadwidth, start_y, mLinePaint);
            // 纵向的
            canvas.drawLine(start_x, startPosition, start_x, broadwidth, mLinePaint);
        }
    }

    /**
     * 生成可以防止棋子的位置数组
     */
    private void initPositionInfos(int startP, int broadwidth) {
        if (!isInitPosition) {
            isInitPosition = true;
            for (int i = 0; i < numberRow; i++) {
                for (int j = 0; j < numberRow; j++) {
                    int x = startP + j * divRow;
                    int y = startP + i * divRow;
                    positions[j][i] = (y << 16) + x;
                    if (isDebug) {
                        LogUtils.d("i,j" + i + "," + j + "," + "x,y" + x + "," + y + "," + positions[i][j]);
                    }
                }
            }
        }
    }

    /**
     * 根据配置画出一个图形
     *
     * @param canvas
     */
    private void drawByConfig(Canvas canvas, PointU p, DrawConfig config) {

        ChessBoard.SIDE side = p.belong;

        if (config.shape == DrawConfig.Shape.CIRCLE) {
            if ((side == ChessBoard.SIDE.BLACK) || (side == ChessBoard.SIDE.WHITE)) {
                if (colorSchema.mBlackBitmap != null && colorSchema.mWhiteBitmap != null) {
                    //drawable

                    if (side == ChessBoard.SIDE.BLACK) {

                    } else {

                    }

                } else {
                    // color
                    if (side == ChessBoard.SIDE.BLACK) {
                        mWhitePaint.setColor(getResources().getColor(colorSchema.colorBlack));
                    } else {
                        mWhitePaint.setColor(getResources().getColor(colorSchema.colorWhite));
                    }

//                    if (isDebug) {
//                        //最大分值/总得份数
//                        long div = RC.SCORES[winNumber] / 0xff;
//                        int alpha = (int) ((p.score+50) / div);
//                        mWhitePaint.setAlpha(alpha);
//                    }

                    //mWhitePaint.setColor(getResources().getColor(mDrawConfig.color));
                    canvas.drawCircle(mDrawConfig.x, mDrawConfig.y, mDrawConfig.r, mWhitePaint);
                }
            } else if (side == ChessBoard.SIDE.DEBUG) {

                mWhitePaint.setColor(getResources().getColor(mDrawConfig.color));
                canvas.drawCircle(mDrawConfig.x, mDrawConfig.y, mDrawConfig.r, mWhitePaint);
            }

        }
    }


    public SurfaceViewTempalte(Context context) {
        this(context, null);
    }

    public SurfaceViewTempalte(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {

        mWidth = Utils.getScreentWidth(getContext());
        mHeight = mWidth;
        mDrawConfig.r = (mWidth - marginEdge * 2) / numberRow;
        initPaint();
        mHolder = getHolder();
        mHolder.addCallback(this);
        setOnTouchListener(this);
    }

    private void initPaint() {
        mWhitePaint = new Paint();
        mBlackPaint = new Paint();
        mLinePaint = new Paint();
        mWhitePaint.setColor(getResources().getColor(colorSchema.colorWhite));
        mWhitePaint.setAntiAlias(true);
        mBlackPaint.setColor(getResources().getColor(colorSchema.colorBlack));
        mBlackPaint.setAntiAlias(true);
        mLinePaint.setColor(getResources().getColor(colorSchema.colorBackground));
        mLinePaint.setStrokeWidth(0.6f);
        mLinePaint.setAntiAlias(true);
    }


    /**
     * 视图创建
     *
     * @param holder
     */
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mDrawThread.start();
    }

    /**
     * 视图改变内容
     *
     * @param holder
     * @param format
     * @param width
     * @param height
     */
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    /**
     * 视图销毁
     *
     * @param holder
     */
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isRunning = false;
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(mWidth, mHeight);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        mWidth = getWidth();
        mHeight = getHeight();
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {


        if (isCanTouch) {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    isTouching = true;
                    break;
                case MotionEvent.ACTION_MOVE:
                    //画出当前的预览
                    Point point = calPosition(event.getX(), event.getY());
                    notifyReDraw(point.x, point.y, R.color.main_green);
                    mTouchPoint.x = point.x;
                    mTouchPoint.y = point.y;
                    mTouchPoint.belong = ChessBoard.SIDE.DEBUG;
                    break;
                case MotionEvent.ACTION_UP:
                    isTouching = false;
                    Point pointup = calPosition(event.getX(), event.getY());
                    notifyMoveFinishObserver(pointup.x, pointup.y);
                    notifyReDraw(pointup.x, pointup.y, android.R.color.holo_red_light);

                    break;
            }
        }

        return true;
    }

    private void notifyReDraw(int x, int y, int color) {
        //  positions[i][j] = (y<<16) + x&0xff;
        // 高16位表示y，低16位表示x,屏幕的像素位置
        mDrawConfig.x = positions[x][y] & 0xffff;
        mDrawConfig.y = positions[x][y] >> 16;
        mDrawConfig.color = color;
        mDrawConfig.shape = DrawConfig.Shape.CIRCLE;
        needReDraw = true;
        if (isDebug)
            LogUtils.d("cal x,y = " + x + "," + y + "," + mDrawConfig.x + "," + mDrawConfig.y + "," + positions[x][y]);
    }

    /**
     * 根据点击的位置计算出在棋盘上的位置
     *
     * @param x 点击松开的x
     * @param y 点击松开的x
     * @return 在棋盘的位置
     */
    private Point calPosition(float x, float y) {
        Point point = new Point();

        //计算的起始位置修改
        int x100 = (int) ((x - (marginEdge + divRow / 2)) * 100);
        int y100 = (int) ((y - (marginEdge + divRow / 2)) * 100);
        int div100 = (int) (divRow * 100);

        point.x = (x100 + 50) / div100;
        point.y = (y100 + 50) / div100;
        if (isDebug) {
            LogUtils.d("div=" + divRow + "originInfo: x= " + x + ",y=" + y);
            LogUtils.d("div=" + divRow + "touchinfo: x=" + (x - marginEdge) / divRow + ",y=" + (y - marginEdge) / divRow);
            LogUtils.d("div=" + divRow + "calInfo: x= " + point.x + ",y=" + point.y);
        }
        return point;
    }


    @Override
    public void onAction(ChessBoard.ACTION action, ChessBoard.SIDE side) {
        switch (action) {
            case RETRACT:
                break;
            case NORMAL:
                isCanTouch = true;
                needReDraw = true;
                break;
            case RESTART:
                isCanTouch = true;
                needReDraw = true;
                break;
            case AI://AI正在下棋
                isCanTouch = false;
                //needReDraw=true;
                break;
        }
    }
}
